package com.jiang.jixiang.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.CountryCodeBean;
import com.jiang.jixiang.bean.UserInfoBean;
import com.jiang.jixiang.databinding.ActivityUserinfoBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.adapter.CountryAdapter;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.bottomdialog.PopBottonDialog;
import com.ws.universal.tools.countdown.CountDown;
import com.ws.universal.tools.countdown.TimeCount;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.newsletter.SlideInOutLeftItemAnimator;
import com.ws.universal.tools.permission.AppActivityTarget;
import com.ws.universal.tools.permission.PermissionListener;
import com.ws.universal.tools.permission.SettingExecutor;
import com.ws.universal.tools.takephoto.app.TakePhoto;
import com.ws.universal.tools.takephoto.app.TakePhotoImpl;
import com.ws.universal.tools.takephoto.model.InvokeParam;
import com.ws.universal.tools.takephoto.model.TContextWrap;
import com.ws.universal.tools.takephoto.model.TResult;
import com.ws.universal.tools.takephoto.permission.InvokeListener;
import com.ws.universal.tools.takephoto.permission.PermissionManager;
import com.ws.universal.tools.takephoto.permission.TakePhotoInvocationHandler;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.PermissionUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ThreadUtils;
import com.ws.universal.tools.utils.ToastUtils;
import com.ws.universal.tools.utils.glide.GlideUtils;
import com.ws.universal.tools.wsui.widget.QMUIRoundButton;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoActivity extends BaseActivity implements InvokeListener, TakePhoto.TakeResultListener, NetWorkListener, PermissionListener {
    private ActivityUserinfoBinding binding;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private UserInfoBean userInfoBean;
    private int requestCodeCamera = 10005;
    private int updateType = 1;
    private CountryCodeBean countryCodeBean;
    private CountryAdapter countryAdapter;
    private TimeCount timeCount;

    @Override
    protected void initCreate(Bundle savedInstanceState) {

        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityUserinfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        getTakePhoto().onCreate(savedInstanceState);
        EventBusUtil.resgisterEventBus(this);

    }

    @Override
    protected void initView() {
        binding.titleLeftBtn.setOnClickListener(view -> {
            onBackPressed();
        });
        binding.titleTextTv.setText(R.string.personal_center);

        binding.llBtnUpdateName.setOnClickListener(view -> {
           /* Bundle bundle = new Bundle();
            bundle.putInt("updateType", 1);
            bundle.putString("userName", binding.tvUserName.getText().toString().trim());
            */
            updateType = 1;
            showSelectImgDialog();
        });

        binding.llBtnUpdatePhone.setOnClickListener(view -> {
            /*Bundle bundle = new Bundle();
            bundle.putInt("updateType", 2);
            bundle.putString("oldPhone", binding.tvPhoen.getText().toString().trim());
            bundle.putString("oldAre", binding.tvArea.getText().toString().trim());
            */
            updateType = 2;
            showSelectImgDialog();

        });
        binding.llBtnUpdateEmail.setOnClickListener(view -> {
           /* Bundle bundle = new Bundle();
            bundle.putInt("updateType", 3);
            bundle.putString("oldEmail", binding.tvEmail.getText().toString().trim());
            */

        });

        binding.rlMeHead.setOnClickListener(view -> {
            PermissionUtils.getInstance().CheckPermissions(this, requestCodeCamera, PermissionUtils.Permission_CameraAndWrite);

        });

        //退出登录
        binding.btnExit.setOnClickListener(view -> {
            CacheUtils.setBoolean(Constants.isLogin, false);
            CacheUtils.setString(Constants.token, "");
            PubDiaUtils.getInstance().clearUserInfo();
            //ManageActivity.removeActivity(UserCenterFragment.class.getSimpleName());
            BaseBusData baseBusData = new BaseBusData(BusCode.LogOut);
            EventBusUtil.postEvent(baseBusData);
            finish();


        });


        timeCount = new TimeCount();
        timeCount.setCountDown(new CountDown() {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetCode.setEnabled(false);
                //binding.tvGetCode.setText(StringUtils.getString("重新发送", "(", millisUntilFinished / 1000 + ")"));
                btnGetCode.setText(StringUtils.getString(millisUntilFinished / 1000));
            }

            @Override
            public void onTickFinish() {
                btnGetCode.setText(R.string.get_code);
                btnGetCode.setEnabled(true);
                btnGetCode.setTextColor(ContextCompat.getColor(getContext(), R.color.text_minor_color));
            }
        });

        loadCountry();
        loadData();
    }



    private void loadData() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        okHttpModel.post(ApiUrl.getUserInfo_Api, params, ApiUrl.getUserInfo_Api_ID, this);
    }

    /*用户更改头像*/
    private void updateUserAvatar(String path) {
        Map<String, String> params = new HashMap<>();
        params.put("type", "avatar");
        params.put("avatar", path);
        okHttpModel.post(ApiUrl.updateInfo_Api, params, ApiUrl.updateInfo_Api_ID, this);
    }

    private void getCode() {
        Map<String, String> params = new HashMap<>();
        params.put("type", "update");
        params.put("area", areaParams);
        params.put("phone", phoneParams);
        okHttpModel.post(ApiUrl.smsCode_Api, params, ApiUrl.smsCode_Api_ID, this);
    }

    private void loadCountry() {
        okHttpModel.post(ApiUrl.getCountryCode_Api, null, ApiUrl.getCountryCode_Api_ID, this);
    }

    private PopBottonDialog updateInfoDialog;// 更改用户信息

    public void showSelectImgDialog() {

        updateInfoDialog = PopBottonDialog.create(getSupportFragmentManager()).setLayoutRes(R.layout.dialog_update_userinfo).setViewListener(new PopBottonDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                initSelectImgDia(v);
            }


        }).setDimAmount(0.3f).setTag("showSelectImgDialog");

        updateInfoDialog.show();

    }

    private TextView btnGetCode;

    private void initSelectImgDia(View view) {

        LinearLayout llTop = view.findViewById(R.id.llTop);
        LinearLayout llCountry = view.findViewById(R.id.llCountry);

        EditText userName = view.findViewById(R.id.edUserName);
        LinearLayout llCountryCode = view.findViewById(R.id.llCountryCode);
        TextView tvArea = view.findViewById(R.id.tvArea);
        EditText edNew = view.findViewById(R.id.edNew);

        LinearLayout llSend = view.findViewById(R.id.llSend);
        btnGetCode = view.findViewById(R.id.btnGetCode);

        ImageView imgBack = view.findViewById(R.id.imgBack);
        RecyclerView rlRecycleView = view.findViewById(R.id.rlRecycleView);

        LinearLayout llUpdateName = view.findViewById(R.id.llUpdateName);
        LinearLayout llNewLayout = view.findViewById(R.id.llNewLayout);


        QMUIRoundButton btnSubmit = view.findViewById(R.id.btnSubmit);
        btnSubmit.setChangeAlphaWhenPress(true);


        countryAdapter = new CountryAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rlRecycleView.setLayoutManager(layoutManager);
        //binding.rlRecycleView.addItemDecoration(decoration = new CustomItemDecoration(this));
        rlRecycleView.setItemAnimator(new SlideInOutLeftItemAnimator(rlRecycleView));
        rlRecycleView.setAdapter(countryAdapter);


        if (updateType == 1) {
            userName.setHint(userInfoBean.getNick());
            llUpdateName.setVisibility(View.VISIBLE);
            llNewLayout.setVisibility(View.GONE);

        } else {
            llUpdateName.setVisibility(View.GONE);
            llNewLayout.setVisibility(View.VISIBLE);
            if (updateType == 2) {
                btnSubmit.setText(getString(R.string.next));

            }
        }


        llCountryCode.setOnClickListener(v -> {
            hideSoftInput(llTop);
            llTop.setVisibility(View.GONE);

            ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    if (countryCodeBean != null) {

                        countryAdapter.addData(countryCodeBean.getList());
                        llCountry.setVisibility(View.VISIBLE);
                    }
                }
            }, 300);


        });

        imgBack.setOnClickListener(v -> {
            llTop.setVisibility(View.VISIBLE);
            llCountry.setVisibility(View.GONE);
        });

        countryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                tvArea.setText(countryAdapter.getData().get(position).getArea());
                llTop.setVisibility(View.VISIBLE);
                llCountry.setVisibility(View.GONE);
            }
        });

        btnSubmit.setOnClickListener(v -> {
            if (updateType == 1) {
                userNameParams = userName.getText().toString().trim();
                if (TextUtils.isEmpty(userNameParams)) {
                    ToastUtils.showShort(getString(R.string.nickname_cannot_be_empty));
                    return;
                }
                updateInfoDialog.dismiss();
                updateUserInfo();

            } else {
                if (updateType == 2) {
                    phoneParams = edNew.getText().toString().trim();
                    areaParams = tvArea.getText().toString().trim();
                    if (TextUtils.isEmpty(phoneParams)) {
                        ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
                        return;
                    }
                    updateType = 3;

                    edNew.getText().clear();
                    edNew.setHint(getString(R.string.verification_code));
                    btnSubmit.setText(getString(R.string.update));
                    llCountryCode.setVisibility(View.GONE);
                    llSend.setVisibility(View.VISIBLE);
                    getCode();

                } else {
                    codeParams = edNew.getText().toString().trim();
                    if (TextUtils.isEmpty(codeParams)) {
                        ToastUtils.showShort(getString(R.string.verification_code_cannot_be_empty));
                        return;
                    }
                    updateInfoDialog.dismiss();
                    updateUserInfo();
                }

            }


        });

        btnGetCode.setOnClickListener(view1 -> {
            if (StringUtils.isEmpty(edNew.getText().toString())) {
                ToastUtils.showShort(getString(R.string.phone_cannot_be_empty));
                return;
            }
            hideSoftInput(btnGetCode);
            showProgressDialog(false);
            getCode();
        });

    }

    private String userNameParams;
    private String phoneParams;
    private String codeParams;
    private String areaParams;

    /*用户更改头像*/
    private void updateUserInfo() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        if (updateType == 1) {
            params.put("type", "nick");
            params.put("nick", userNameParams);
            okHttpModel.post(ApiUrl.updateInfo_Api, params, ApiUrl.updateInfo_Api_ID, this);
        } else {
            params.put("type", "mobile");
            params.put("area", areaParams);
            params.put("phone", phoneParams);
            params.put("code", codeParams);
            okHttpModel.post(ApiUrl.updateInfo_Api, params, ApiUrl.updateInfo_Api_ID2, this);

        }

    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.getUserInfo_Api_ID:
                userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                PubDiaUtils.getInstance().saveUserInfo(data.toString());
                GlideUtils.CreateImageRound(userInfoBean.getAvatar(), binding.imgMeHead, R.mipmap.icon_def_head, R.mipmap.icon_def_head);
                binding.tvUserName.setText(userInfoBean.getNick());
                binding.tvPhoen.setText(userInfoBean.getMobile());
                binding.tvArea.setText(StringUtils.getString("+", TextUtils.isEmpty(userInfoBean.getArea()) ? CacheUtils.getString(Constants.areaParams) : userInfoBean.getArea()));


                break;

            case ApiUrl.smsCode_Api_ID:
            case ApiUrl.emailCode_Api_ID:

                stopProgressDialog();
                int time = data.optInt("time");
                timeCount.setmMillisInFuture(time * 1000);
                timeCount.start();
                ToastUtils.showLong(commonality.getMessage(), 3000);

                break;

            case ApiUrl.fileUpload_Api_ID:

                String path = data.optString("id");
                updateUserAvatar(path);
                break;

            case ApiUrl.updateInfo_Api_ID:

                binding.loadingHeadBackground.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        binding.loadingAvatar.setBackgroundResource(R.mipmap.icon_user_uoload);
                        if (binding.loadingAvatar.getBackground() instanceof AnimationDrawable) {
                            AnimationDrawable animationDrawable = (AnimationDrawable) binding.loadingAvatar.getBackground();
                            animationDrawable.stop();
                        }
                        binding.loadingAvatar.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                binding.loadingAvatar.setVisibility(View.GONE);
                                binding.loadingHeadBackground.setVisibility(View.GONE);
                                BaseBusData busData = new BaseBusData(BusCode.updateUserInfoAvatar);
                                EventBusUtil.postEvent(busData);
                            }
                        }, 300);
                    }
                }, 2000);

                break;
            case ApiUrl.updateInfo_Api_ID2:
                BaseBusData baseBusData = new BaseBusData(BusCode.updateUserInfo);
                EventBusUtil.postEvent(baseBusData);

                break;
            case ApiUrl.getCountryCode_Api_ID:
                countryCodeBean = GsonUtils.parseJObject(data.toString(), CountryCodeBean.class);
                break;
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }


    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void takeSuccess(TResult result) {
        LogcatUtils.e(" zw takeSuccess：" + result.getImage().getCompressPath());
        Glide.with(this).load(new File(result.getImage().getCompressPath())).into(binding.imgMeHead);
        postBackGroundImg(result.getImage().getCompressPath());

    }

    private void postBackGroundImg(String compressPath) {
        binding.loadingAvatar.setBackgroundResource(com.ws.universal.tools.R.drawable.user_loading_anim);
        if (binding.loadingAvatar.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) binding.loadingAvatar.getBackground();
            animationDrawable.start();
        }
        binding.loadingHeadBackground.setVisibility(View.VISIBLE);
        binding.loadingAvatar.setVisibility(View.VISIBLE);
        ArrayList<File> files = new ArrayList<>();
        files.add(new File(compressPath));
        okHttpModel.postUpLoadFile(ApiUrl.fileUpload_Api, files, ApiUrl.fileUpload_Api_ID, this);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogcatUtils.e("zw takeFail:" + msg);
    }

    @Override
    public void takeCancel() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)  //3.0之后，需要加注解
    public void onEventMainThread(BaseBusData data) {
        switch (data.action) {
            case BusCode.updateUserInfo:
                loadData();
                break;

        }
    }

    @Override
    protected void FinishDesTroy() {
        EventBusUtil.unResgisterEventBus(this);
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    @Override
    public void onPermissionSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        if (requestCode == requestCodeCamera) {
            PubDiaUtils.getInstance().showSelectImgDialog(getSupportFragmentManager(), getContext(), getTakePhoto(), 1, false, false);
        }
    }

    @Override
    public void onPermissionFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        PubDiaUtils.getInstance().showTwoBtnDialog(getContext(), getString(R.string.permission_hit), getString(R.string.permission_content), getString(R.string.cancel), getString(R.string.sure), new PubDiaUtils.PublicDiaologCallback() {
            @Override
            public void onConfirm() {
                if (mSettingService == null) {
                    mSettingService = new SettingExecutor(new AppActivityTarget(getActivity()), 300);
                }
                mSettingService.execute();
            }

            @Override
            public void onCancel() {

            }
        });
    }
}
